<template>
  <div class="edit-pic">
    <div class="w-40 h-40">
      <img class="w-full h-full" :src="avatarUrl" alt="" ref="uploadImgWidth">
    </div>
    <div class="submit">
      <van-uploader multiple :max-count="1" :after-read="getImageInfo" :max-size="1024 * 1024" @oversize="onOversize">
        <YuButton>上传头像</YuButton>
      </van-uploader>
      <YuButton @click="getAvatarUploadFn">保存</YuButton>
    </div>

  </div>
</template>

<script setup>
import {useStore} from "@/store/index";
import {reactive, ref, toRefs, watchEffect} from "vue";
import YuButton from '@/components/YuButton/index.vue'
import {getAvatarUpload} from "@/api/updateInfo/index";
import {Toast} from "vant";


const store = useStore()
const data = reactive({
  avatarUrl: '', // 上传文件展示的图片
  uploadFile: '', // 上传文件的file
})
// 图片宽度
const uploadImgWidth = ref()

const { avatarUrl } = toRefs(data)

// 监听userInfo数据的变化
watchEffect(() => {
  if (store.userInfo) {
    data.avatarUrl = store.userInfo.avatarUrl
  }
})

// 获取上传图片的信息
const getImageInfo = (e) => {
  data.avatarUrl = e.content
  data.uploadFile = e.file
}

// 调用接口上传图片

const getAvatarUploadFn = () => {
  if (data.uploadFile) {
    let formData = new FormData()
    // 转换为formData格式
    formData.append('imgFile', data.uploadFile)
    getAvatarUpload(formData, {imgSize: 2000}).then(res => {
      if (res.code === 200) {
        data.uploadFile = null
        Toast('上传成功');
      }
    })
  }
}

// 检测上传图像大小
const onOversize = () => {
  Toast('文件大小不能超过 1M');
};

</script>

<style scoped lang="scss">
.edit-pic {
  display: flex;
  flex-direction: column;
  align-items: center;

  .submit {
    margin-top: 5px;
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
}
</style>
